import { defineConfig, loadEnv } from 'vite'
import path, { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import legacy from '@vitejs/plugin-legacy'
import AutoImport from 'unplugin-auto-import/vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import Components from 'unplugin-vue-components/vite'
import vueJsx from "@vitejs/plugin-vue-jsx"
import electron from 'vite-plugin-electron'
import postCssPxToRem from 'postcss-pxtorem'
import autoprefixer from 'autoprefixer'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // command: serve build
  // mode: development production
  // base 地址
  const systemPath = loadEnv(mode, process.cwd()).VITE_SYSTEMPATH
  const publicPath: string = command === 'serve' ? `/${systemPath}` : `./${systemPath}`;
  const proxyIp = `https://${loadEnv(mode, process.cwd()).VITE_PROXYIP}:${loadEnv(mode, process.cwd()).VITE_PROXYPORT}/`;
  return {
    plugins: [
      vue(),
      vueJsx({}),
      // 按需引入components，封装的公共组件，会自动import
      Components({
        dirs: ['src/components'],
        resolvers: [],
        directoryAsNamespace: true
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [resolve(process.cwd(), `public/svgs`)],
        // 指定symbolId格式
        // 用<symbol>标记的作用是定义一个图像模板，使用<use>标记实例化它，然后在SVG文档中反复使用。
        // <symbol>本身不会输出任何图像，只有使用<use>实例化后才会显示。
        symbolId: 'icon-[name]',
      }),
      //传统浏览器兼容性支持--需要支持的放开注释即可
      legacy({
        targets: ['chrome >= 56', 'IE >= 11', 'Firefox >= 70', 'Edge >= 44'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        modernPolyfills: true
      }),
      AutoImport({
        imports: ["vue", "vue-i18n"], // 自动导入vue和vue-i18n相关函数
        dts: "auto-imports.d.ts", // 生成 `auto-import.d.ts` 全局声明
        eslintrc: {
          enabled: true, // .eslintrc-auto-import.json
        }
      }),
      //直接在script标签中写name属性
      VueSetupExtend(),
      // https://github.com/electron-vite/vite-plugin-electron/tree/main/packages/electron-renderer#electron-renderervite-serve
      electron([
        {
          entry: "electron/main.ts",
          vite: { build: { outDir: "dist/electron/main" } },
        },
        {
          entry: "electron/preload.ts",
          vite: { build: { outDir: "dist/electron/preload" } },
        }
      ])
    ],
    base: "./", // 配合 electron 打包
    root: process.cwd(),
    server: {
      host: "0.0.0.0",
      port: "8080",
      https: false,
      proxy: {
        '/': {
          target: proxyIp,
          secure: false,
          changeOrigin: true,
          bypass: function (req, res, proxyOptions) {
            if ((req.url as any).indexOf(publicPath) === 0) {
              return req.url
            }
          }
        }
      },
      watch: {
        usePolling: true
      }
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src")
      }
    },
    css: {
      preprocessorOptions: {},
      postcss: {
        plugins: [
          postCssPxToRem({
            // 自适应，px>rem转换
            rootValue: 16, // 1rem的大小
            propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
          }),
          autoprefixer({
            // 自动添加前缀
            overrideBrowserslist: [
              'Android 4.1',
              'iOS 7.1',
              'Chrome > 31',
              'ff > 31',
              'ie >= 8',
              //'last 2 versions', // 所有主流浏览器最近2个版本
            ],
            grid: true,
          }),
        ],
      },
    },
    esbuild: {
      jsxFactory: 'h',
      jsxFragment: 'Fragment',
      jsxInject: 'import { h } from "vue";'
    },
    build: {
      assetsDir: 'static',
      rollupOptions: {
        external: ["EvoEmap"],
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id: any) {
            if (id.includes('node_modules')) {
              return 'vendor' //代码分割为第三方包
            }
          },
        }
      },
      minify: "terser",
      terserOptions: {
        // 打包后移除console和注释
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      }
    }
  }
})
